#include "VText.h"
#include "VMain.h"

VTTFFont* VText::s_font = NULL;

VText::VText(void) :
    _r(-1), _g(-1), _b(-1),  // 255 white
    _texture(INVALID_TEXTURE), _text("")
{
    createStaticFont();

    _font = s_font;

    genTexture();
}

VText::VText(const std::string& text /*= string()*/, VTTFFont* font /*= */)
{
    createStaticFont();

    if (!font)
    {
        _font = s_font;
    }
    else
    {
        _font = font;
    }


    _text = text;
    genTexture();
}

VText::~VText(void)
{

}

void VText::setText(const std::string& text)
{
    int _width, _height;

    _text = text;
    genTexture();

    _font->sizeText(text, &_width, &_height);

    resize(_width, _height);
}

void VText::createStaticFont(void)
{
    if (VText::s_font == NULL)
    {
        bool loaded = true;
        VTTFFont::init();
        VText::s_font = new VTTFFont;
        loaded = VText::s_font->load(GET_FONT_PATH("default.ttf"), 20);
    }
}

bool VText::render() const
{
    if (!VRRWidget::render())
    {
        return false;
    }

    static const GLfloat texCoords[] =
    {
        0, 0,
        0, 1,
        1, 0,
        1, 1
    };


    GLfloat vertexes[] =
    {
        0, 0,
        0, _h,
        _w, 0,
        _w, _h
    };



    glPushMatrix();

    glTranslatef(_x, _y, 0);

    glEnable(GL_TEXTURE_2D);

    glBindTexture(GL_TEXTURE_2D, _texture);

    glEnableClientState(GL_VERTEX_ARRAY);

    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glTexCoordPointer(2, GL_FLOAT, 0, texCoords);

    glVertexPointer(2, GL_FLOAT, 0, vertexes);

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    glDisableClientState(GL_VERTEX_ARRAY);

    glDisableClientState(GL_TEXTURE_COORD_ARRAY);


    glPopMatrix();

    return true;

}


bool VText::genTexture()
{
    if (_texture != INVALID_TEXTURE)
    {
        VMain::deleteTexture(&_texture);
    }

    int w, h;

    _font->sizeText(_text, &w, &h);

    _texture = _font->renderText(_text, _r, _g, _b);

    if (_texture != INVALID_TEXTURE)
    {
        return true;
    }

    return false;
}


void VText::setFont(VTTFFont* font)
{
    this->_font = font;
    genTexture();
}

const std::string& VText::text() const
{
    return this->_text;
}

VTTFFont* VText::font() const
{
    return this->_font;
}

GLuint VText::getTexture() const
{
    return this->_texture;
}

